import { Elysia } from 'elysia';

import { MayError } from '@/utils/error';
import { logger } from '@/utils/logger';

/**
 * Access 日志中间件
 * 记录所有 HTTP 请求的访问日志
 */
export const accessLoggerMiddleware = new Elysia({ name: 'access-logger' })
  .derive(({ request }) => {
    return {
      userAgent: request.headers.get('user-agent'),
    };
  })
  .onBeforeHandle(({ request, userAgent }) => {
    logger.info({
      method: request.method,
      url: request.url,
      userAgent,
      msg: '🕊️ 收到请求',
    });
  })
  .onAfterHandle(({ request, set, userAgent }) => {
    // 记录请求完成
    logger.info({
      method: request.method,
      url: request.url,
      status: set.status,
      userAgent,
      msg: '🎯 请求成功',
    });
  })
  .onError(({ request, error, userAgent }) => {
    // 记录请求错误
    if (error instanceof MayError) {
      logger.error({
        method: request.method,
        url: request.url,
        userAgent,
        err: error.cause,
        msg: `❌ ${error.message}`,
        ...error.meta,
      });
    } else {
      logger.error({
        method: request.method,
        url: request.url,
        userAgent,
        err: error,
        msg: '💥 请求失败',
      });
    }
  })
  .as('scoped');
